import { PlusOutlined } from '@ant-design/icons';
import { useEffect } from 'react';
import { Button, Divider, message, Popconfirm, Image, Select } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import CreateForm from './components/CreateForm';
import styles from '../../../global.less';
import FormItem from 'antd/lib/form/FormItem';
import UploadImg from '@/components/UploadImg';
import { queryRule, updateRule, addRule, removeRule, getPositionList } from './service';
/**
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields) => {
  const hide = message.loading('正在添加');

  try {
    await addRule({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 *
 * @param fields
 */

const handleUpdate = async (fields) => {
  const hide = message.loading('正在配置');

  try {
    await updateRule(fields);
    hide();
    message.success('配置成功');
    return true;
  } catch (error) {
    hide();
    message.error('配置失败请重试！');
    return false;
  }
};
/**
 * 删除节点
 *
 * @param selectedRows
 */

const handleRemove = async (selectedRows, actionRef) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await removeRule(selectedRows);
    hide();
    message.success('删除成功，即将刷新');
    actionRef.current.reload();
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};
const { Option } = Select;
const TableList = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState(false);
  const [stepFormValues, setStepFormValues] = useState({});
  const actionRef = useRef();
  const [count, setCount] = useState();
  const [positionData, setPositionData] = useState([]);
  const [facePicture, setFacePicture] = useState(null);
  const [status, setStatus] = useState(0);
  const handleStatus = (e) => {
    setStatus(e);
  };
  const handleSetFacePicture = (payload) => {
    setFacePicture(payload.url);
  };
  const handlePosition = () => {
    getPositionList().then((res) => {
      const { data, code } = res;
      code === 0 ? setPositionData(data) : null;
    });
  };
  useEffect(() => {
    return handlePosition();
  }, []);
  const columns = [
    {
      title: '位置',
      dataIndex: 'position',
      render: (dom, entity) => {
        return <a>{dom === 'HOME' ? '页面' : '导航图'}</a>;
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <Select placeholder="请选择位置" allowClear>
            {positionData.map((item, index) => {
              return (
                <Option value={item} key={index}>
                  {item === 'HOME' ? '页面' : '导航图'}
                </Option>
              );
            })}
          </Select>
        );
      },
    },
    {
      title: '排序',
      dataIndex: 'sort',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '排序必填项',
          },
        ],
      },
    },
    {
      title: '主标题',
      dataIndex: 'mainTitle',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '主标题必填项',
          },
        ],
      },
    },
    {
      title: '副标题',
      dataIndex: 'title',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '副标题必填项',
          },
        ],
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueEnum: {
        0: {
          text: '启用',
          status: 'Processing',
        },
        1: {
          text: '禁用',
          status: 'Error',
        },
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <Select placeholder="请选择状态" value={status} onChange={handleStatus}>
            <Option value={0}>启用</Option>
            <Option value={1}>禁用</Option>
          </Select>
        );
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '状态必选项',
          },
        ],
      },
    },
    {
      title: '图片地址',
      dataIndex: 'url',
      hideInSearch: true,
      render: (_, record) => {
        return <Image className={styles.img_div} src={_} />;
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <>
            {stepFormValues ? (
              <FormItem name="icon">
                <UploadImg
                  imgUrl={facePicture}
                  showImgUrl={facePicture}
                  subpath="banner"
                  handleSetFacePicture={handleSetFacePicture}
                />
              </FormItem>
            ) : (
              <FormItem name="icon">
                <UploadImg subpath="banner" handleSetFacePicture={handleSetFacePicture} />
              </FormItem>
            )}
          </>
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => {
        return (
          <>
            <a
              onClick={() => {
                handleModalVisible(true);
                setStepFormValues(record);
                setFacePicture(record.url);
              }}
            >
              修改
            </a>
            <Divider type="vertical" />
            <Popconfirm
              title="确定删除配置吗吗?"
              onConfirm={() => {
                handleRemove(record.id, actionRef);
              }}
              okText="是"
              cancelText="否"
            >
              <a>删除</a>
            </Popconfirm>
          </>
        );
      },
    },
  ];
  return (
    <PageContainer>
      <ProTable
        headerTitle="配置列表"
        actionRef={actionRef}
        rowKey="id"
        bordered
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            onClick={() => {
              setStepFormValues();
              setFacePicture();
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={(params, sorter, filter) => queryRule({ ...params, sorter, filter })}
        columns={columns}
        postData={(params) => {
          const { list, total } = params;
          setCount(total);
          return list||[];
        }}
        pagination={{
          defaultPageSize: 30,
          showSizeChanger: false,
          showTitle: false,
          total: count,
          showTotal: (total) => `共${total}条`,
        }}
      />

      <CreateForm
        title={stepFormValues ? '修改配置' : '新增配置'}
        width={800}
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={async (value) => {
            value.url = facePicture;
            value.status = status;
            stepFormValues ? (value.id = stepFormValues.id) : null;
            const success = stepFormValues ? await handleUpdate(value) : await handleAdd(value);

            if (success) {
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="id"
          bordered
          type="form"
          form={{
            initialValues: stepFormValues ? stepFormValues : null,
            layout: 'horizontal',
            labelAlign: 'rihgt',
            labelCol: { span: 7 },
            wrapperCol: { span: 20 },
          }}
          columns={columns}
        />
      </CreateForm>
    </PageContainer>
  );
};

export default TableList;
